var cluster = require('cluster');
var EventEmitter = require('events').EventEmitter;

var broker = new EventEmitter();

if (cluster.isWorker) {

	process.on('message', function (msg) {
		var event = msg['event'];
		var channel = msg['channel'];
		var message = msg['message'];
		if (event === 'publish' && channel && message) {
			broker.emit('message', channel, message);
		}
	});

	broker.subscribe = function (channel) {
		process.send({
			event: 'subscribe',
			channel: channel
		});
	};

	broker.unsubscribe = function (channel) {
		process.send({
			event: 'unsubscribe',
			channel: channel
		})
	};

	broker.publish = function (channel, message) {
		process.send({
			event: 'publish',
			channel: channel,
			data: message
		});
	};
}

module.exports = broker;
